import request from '@/utils/request'
import type {
  ApiResponse,
  PageResponse,
  NoteDaily,
  NoteDocument,
  NoteCategory,
  NoteQuery,
  NoteStats
} from '@/types/api'
import { mockData, mockDelay } from '@/mock'

// 是否使用mock数据
const USE_MOCK = false

// 获取公开的日常笔记列表
export async function getPublicDailyNotes(params: NoteQuery): Promise<ApiResponse<PageResponse<NoteDaily>>> {
  if (USE_MOCK) {
    await mockDelay()
    return mockData.notes.dailyNotes
  }
  return request({
    url: '/blog/note/daily/list',
    method: 'get',
    params
  })
}

// 获取公开的文档笔记列表
export async function getPublicDocumentNotes(params: NoteQuery): Promise<ApiResponse<PageResponse<NoteDocument>>> {
  if (USE_MOCK) {
    await mockDelay()
    return mockData.notes.documentNotes
  }
  return request({
    url: '/blog/note/document/list',
    method: 'get',
    params
  })
}

// 获取日常笔记详情
export function getDailyNoteDetail(noteId: number): Promise<ApiResponse<NoteDaily>> {
  return request({
    url: `/blog/note/daily/${noteId}`,
    method: 'get'
  }).then(response => {
    // 处理后端返回的数据结构：data.note 包含实际的笔记数据
    if (response.data && response.data.note) {
      return {
        ...response,
        data: response.data.note
      }
    }
    return response
  })
}

// 获取文档笔记详情
export function getDocumentNoteDetail(noteId: number): Promise<ApiResponse<NoteDocument>> {
  return request({
    url: `/blog/note/document/${noteId}`,
    method: 'get'
  }).then(response => {
    // 处理后端返回的数据结构：data.note 包含实际的笔记数据
    if (response.data && response.data.note) {
      return {
        ...response,
        data: response.data.note
      }
    }
    return response
  })
}

// 获取笔记分类列表
export async function getNoteCategories(): Promise<ApiResponse<string[]>> {
  if (USE_MOCK) {
    await mockDelay()
    return mockData.notes.categories
  }
  return request({
    url: '/blog/note/category/list',
    method: 'get'
  })
}

// 获取热门标签
export async function getHotTags(): Promise<ApiResponse<Array<{ name: string; count: number }>>> {
  if (USE_MOCK) {
    await mockDelay()
    return mockData.notes.hotTags
  }
  return request({
    url: '/blog/note/tags/hot',
    method: 'get'
  })
}

// 获取笔记标签列表
export async function getNoteLabels(): Promise<ApiResponse<{labelId: number, labelName: string, color: string}[]>> {
  if (USE_MOCK) {
    await mockDelay()
    return mockData.notes.labels
  }
  return request({
    url: '/blog/note/label/list',
    method: 'get'
  })
}

// 根据标签获取笔记列表
export function getNotesByLabel(labelId: number, params: NoteQuery): Promise<ApiResponse<PageResponse<NoteDaily | NoteDocument>>> {
  return request({
    url: `/blog/note/label/${labelId}/notes`,
    method: 'get',
    params
  })
}

// 搜索笔记
export function searchNotes(params: { keyword: string; type?: string; pageNum?: number; pageSize?: number }): Promise<ApiResponse<PageResponse<NoteDaily | NoteDocument>>> {
  return request({
    url: '/blog/note/search',
    method: 'get',
    params
  })
}

// 获取推荐笔记
export function getRecommendedNotes(limit?: number): Promise<ApiResponse<(NoteDaily | NoteDocument)[]>> {
  return request({
    url: '/blog/note/recommend',
    method: 'get',
    params: { limit }
  }).then(response => {
    // 处理后端返回的数据结构：data.documents 和 data.dailyNotes
    if (response.data && (response.data.documents || response.data.dailyNotes)) {
      const documents = response.data.documents || []
      const dailyNotes = response.data.dailyNotes || []
      return {
        ...response,
        data: [...documents, ...dailyNotes]
      }
    }
    return response
  })
}

// 获取笔记详情（通用函数，根据路由参数判断类型）
export function getNoteDetail(noteId: number, type?: string): Promise<ApiResponse<(NoteDaily | NoteDocument) & { noteType: string }>> {
  // 如果指定了类型，使用对应的接口
  if (type === 'daily') {
    return getDailyNoteDetail(noteId).then(response => ({
      ...response,
      data: { ...response.data, noteType: 'daily' }
    }))
  } else if (type === 'document') {
    return getDocumentNoteDetail(noteId).then(response => ({
      ...response,
      data: { ...response.data, noteType: 'document' }
    }))
  }
  
  // 默认先尝试日常笔记，如果失败再尝试文档笔记
  return getDailyNoteDetail(noteId)
    .then(response => ({
      ...response,
      data: { ...response.data, noteType: 'daily' }
    }))
    .catch(() => 
      getDocumentNoteDetail(noteId).then(response => ({
        ...response,
        data: { ...response.data, noteType: 'document' }
      }))
    )
}

// 获取笔记统计信息
export function getNoteStats(noteId: number): Promise<ApiResponse<NoteStats>> {
  return request({
    url: `/blog/note/${noteId}/stats`,
    method: 'get'
  })
}

// 函数别名，保持向后兼容
export const getDailyNotes = getPublicDailyNotes
export const getDocumentNotes = getPublicDocumentNotes
export const getNoteById = getNoteDetail
export const getHotNotes = getRecommendedNotes